<?php
namespace Menory\Unit\HttpClient\Adapter;

use Menory\Unit\HttpClient\AHttpClient;
use Menory\Unit\HttpClient\HttpClientError;
use Menory\Unit\HttpClient\Response;

class CUrl extends AHttpClient {

    /**
     * @param $url
     * @param string $requestMethod
     * @param null $postFields
     * @param null $headers
     * @return array
     */
    public function send($url, $requestMethod = "get", $postFields = null, $headers = null) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($requestMethod));
//        if (false) {
//            curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
//            curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY_IP);
//            curl_setopt($ch, CURLOPT_PROXYPORT, HTTP_PROXY_PORT);
//            curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
//        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? http_build_query($postFields) : $postFields);
        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        //https request
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (is_array($headers) && 0 < count($headers)) {
            $httpHeaders = $this->getHttpHeaders($headers);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
        }
        $response = new Response();
        $response->setBody(curl_exec($ch));
        $response->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        if (curl_errno($ch)) {
            return [null, new HttpClientError("[" . curl_errno($ch) . "] " . curl_error($ch))];
        }
        curl_close($ch);

        return [$response, null];

    }

}